package com.example.music_project.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class UserDbHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "UserDB";
    private static final int DATABASE_VERSION = 1;

    public static final String TABLE_USERS = "users";
    public static final String COLUMN_USER_ID = "user_id";
    public static final String COLUMN_USER_NAME = "user_name";
    public static final String COLUMN_USER_PASSWORD = "user_password";
    public static final String COLUMN_USER_EMAIL = "user_email";

    // 创建数据表
    private static final String CREATE_TABLE_USERS = "CREATE TABLE " + TABLE_USERS + " ("
            + COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COLUMN_USER_NAME + " TEXT NOT NULL UNIQUE,"
            + COLUMN_USER_PASSWORD + " TEXT NOT NULL,"
            + COLUMN_USER_EMAIL + " TEXT" + ")";

    public UserDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_USERS);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
        onCreate(db);
    }

    /**
     * 添加用户（密码自动哈希）
     */
    public long addUser(String userName, String password, String email) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_NAME, userName);
        values.put(COLUMN_USER_PASSWORD, hashPassword(password)); // 加密密码
        values.put(COLUMN_USER_EMAIL, email);

        long result = db.insert(TABLE_USERS, null, values);
        Log.d("UserDbHelper", "Insert result: " + result);
        return result; // 不关闭db，由SQLiteOpenHelper管理
    }

    /**
     * 验证用户名和密码
     */
    public boolean checkUser(String userName, String password) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_USERS,
                new String[]{COLUMN_USER_PASSWORD},
                COLUMN_USER_NAME + "=?",
                new String[]{userName}, null, null, null);

        boolean isValid = false;
        if (cursor.moveToFirst()) {
            String storedPassword = cursor.getString(0); // 直接获取第一列
            isValid = storedPassword.equals(hashPassword(password)); // 比较哈希值
            Log.d("UserDbHelper", "Password check result: " + isValid);
        }

        cursor.close();
        return isValid; // 不关闭db
    }

    /**
     * 检查用户名是否存在
     */
    public boolean isUserNameExists(String userName) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_USERS,
                new String[]{COLUMN_USER_ID},
                COLUMN_USER_NAME + "=?",
                new String[]{userName}, null, null, null);

        boolean exists = cursor.getCount() > 0;
        cursor.close();
        return exists; // 不关闭db
    }

    /**
     * 更新用户信息（用户名和邮箱）
     */
    public boolean updateUserInfo(String oldUsername, String newUsername, String newEmail) {
        SQLiteDatabase db = this.getWritableDatabase();

        // 检查新用户名是否已被占用
        if (!oldUsername.equals(newUsername) && isUserNameExists(newUsername)) {
            Log.w("UserDbHelper", "用户名已存在: " + newUsername);
            return false;
        }

        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_NAME, newUsername);
        values.put(COLUMN_USER_EMAIL, newEmail);

        int rowsAffected = db.update(
                TABLE_USERS,
                values,
                COLUMN_USER_NAME + "=?",
                new String[]{oldUsername}
        );

        db.close();
        return rowsAffected > 0;
    }

    /**
     * SHA-256密码哈希
     */
    private String hashPassword(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(password.getBytes("UTF-8"));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            throw new RuntimeException("Password hashing failed", e);
        }
    }

    /**
     * 根据用户名查找邮箱
     * @param username
     * @return
     */
    public String getEmailByUsername(String username) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(
                "users",          // 表名
                new String[]{"user_email"}, // 要查询的列
                "user_name = ?",   // WHERE 条件
                new String[]{username}, // WHERE 参数
                null, null, null
        );

        String email = null;
        if (cursor.moveToFirst()) {
            email = cursor.getString(cursor.getColumnIndexOrThrow("user_email"));
        }
        cursor.close();
        return email;
    }
}